//
//  WarnDetailViewController.m
//  Rail
//
//  Created by hychen on 2018/2/28.
//  Copyright © 2018年 Hychen. All rights reserved.
//

#import "WarnDetailViewController.h"
#import "WarnDetailTableViewCell.h"
#import "WarnDetailResultTableViewCell.h"
#import "WarnDetailHandleBtnTableViewCell.h"
#import "WarnDetailDescribeView.h"
#import "WMPlayer.h"
#import "NSDate+Category_lib.h"
#import "HandleWarnViewController.h"

#import "ESPictureBrowser.h"
@interface WarnDetailViewController () <ESPictureBrowserDelegate,WMPlayerDelegate,UIGestureRecognizerDelegate>
{
    WMPlayer *_wmPlayer;
}
@property (nonatomic, strong) ESPictureBrowser *browser;
@property (nonatomic, strong) NSMutableArray *imageUrlArray;
@property (nonatomic, strong) WarnDetailDescribeView *headerView;
@end

@implementation WarnDetailViewController

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //获取设备旋转方向的通知,即使关闭了自动旋转,一样可以监测到设备的旋转方向
//    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
//    //旋转屏幕通知
//    [[NSNotificationCenter defaultCenter] addObserver:self
//                                             selector:@selector(onDeviceOrientationChange:)
//                                                 name:UIDeviceOrientationDidChangeNotification
//                                               object:nil
//     ];
    
    [self.navigationItem addSimpleTitleView:@"报警详情"];
    
    self.isOpenHeader = NO;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"WarnDetailTableViewCell" bundle:nil] forCellReuseIdentifier:NSStringFromClass([WarnDetailTableViewCell class])];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"WarnDetailResultTableViewCell" bundle:nil] forCellReuseIdentifier:NSStringFromClass([WarnDetailResultTableViewCell class])];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"WarnDetailHandleBtnTableViewCell" bundle:nil] forCellReuseIdentifier:NSStringFromClass([WarnDetailHandleBtnTableViewCell class])];
    
    //请求数据
    [self requestWarnData];
}

- (void)setupImageUrl {
    //图片
    NSMutableArray *imageUrlArray = [NSMutableArray array];
    if ([self.model.snapshot_url1 objectIsNotEmpty]) {
        [imageUrlArray addObject:self.model.snapshot_url1];
    }
    if ([self.model.snapshot_url2 objectIsNotEmpty]) {
        [imageUrlArray addObject:self.model.snapshot_url2];
    }
    if ([self.model.snapshot_url3 objectIsNotEmpty]) {
        [imageUrlArray addObject:self.model.snapshot_url3];
    }
    self.imageUrlArray = imageUrlArray;
    
    //图片浏览器
    ESPictureBrowser *browser = [[ESPictureBrowser alloc] init];
    self.browser = browser;
    browser.delegate = self;
}

- (void)setupHeaderView {
    //头部
    WarnDetailDescribeView *headerView = [WarnDetailDescribeView describeView];
    self.headerView = headerView;
    [headerView setFrame:CGRectMake(0, 0, SCREEN_WIDTH, [WarnDetailDescribeView heightForDescribeView:self.model])];
    headerView.model = self.model;
    self.tableView.tableHeaderView = headerView;
    BMWeakSelf
    [headerView setBlockClickImage:^(NSInteger currentIndex, id obj) {
        
        if (currentIndex >= weakSelf.imageUrlArray.count) {
            currentIndex = weakSelf.imageUrlArray.count - 1;
        }
        [self.browser showFromView:weakSelf.view picturesCount:weakSelf.imageUrlArray.count currentPictureIndex:currentIndex];
    }];
    
    [headerView setBlockCliclPlayBtn:^(UIButton *btn) {
        [weakSelf playVideo];
    }];
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)handleWarn {
    if (self.model.recordid.length > 0) {
        HandleWarnViewController *vc = [HandleWarnViewController new];
        BMWeakSelf
        [vc setBlockHandleSuccess:^(NSString *text) {
            weakSelf.model.process_result = @"1";
            weakSelf.model.content = text?:@"";
            NSString *time = [[NSDate date] formatYearMonthDayHourSecond_lib];
            if (time.length > 18) {
                weakSelf.model.process_time = [NSString stringWithFormat:@"%@.0",[[NSDate date] formatYearMonthDayHourSecond_lib]];
            }
            else {
                weakSelf.model.process_time = [NSString stringWithFormat:@"%@",[[NSDate date] formatYearMonthDayHourSecond_lib]];
            }

            //刷新内容
            [weakSelf.tableView reloadData];
            
            if (weakSelf.BlockProcessedWarn) {
                weakSelf.BlockProcessedWarn();
            }
        }];
        vc.recordId = self.model.recordid;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    BOOL hasHandle = [self.model.process_result isEqualToString:@"1"]?YES:NO;
    if (hasHandle) {
        return 6;
    }
    return 7;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row < 5) {
        WarnDetailTableViewCell *cell = [WarnDetailTableViewCell cellWithTableView:tableView class:[WarnDetailTableViewCell class]];
        
        switch (indexPath.row) {
            case 0:
            {
                [cell hideArrow];
                cell.titleLabel.text = @"报警时间";
                cell.contentLabel.text = [BMUtils chineseMMDDHHmmWithServiceTime:self.model.start_time];
            }
                break;
            case 1:
            {
                [cell hideArrow];
                cell.titleLabel.text = @"结束时间";
                cell.contentLabel.text = [BMUtils chineseMMDDHHmmWithServiceTime:self.model.end_time];
            }
                break;
            case 2:
            {
                [cell showArrowWithImage:nil];
                cell.titleLabel.text = @"报警设备";
                cell.contentLabel.text = self.model.device_name?:@"";
            }
                break;
            case 3:
            {
                [cell showArrowWithImage:nil];
                cell.titleLabel.text = @"所在工区";
                cell.contentLabel.text = self.model.area_name?:@"";
            }
                break;
            case 4:
            {
                [cell showArrowWithImage:nil];
                cell.titleLabel.text = @"所属线路";
                cell.contentLabel.text = self.model.line_name?:@"";
            }
                break;
            default:
                break;
        }
        
        return cell;
    }
    else if (indexPath.row == 5) {
        BOOL hasHandle = [self.model.process_result isEqualToString:@"1"]?YES:NO;
        if (hasHandle) {
            WarnDetailResultTableViewCell *cell = [WarnDetailResultTableViewCell cellWithTableView:tableView class:[WarnDetailResultTableViewCell class]];
            //赋值
            cell.model = self.model;
            return cell;
        }
        else {
            WarnDetailTableViewCell *cell = [WarnDetailTableViewCell cellWithTableView:tableView class:[WarnDetailTableViewCell class]];
            cell.titleLabel.text = @"处理结果";
            cell.contentLabel.text = @"未处理";
            return cell;
        }
    }
    else if (indexPath.row == 6) {
        WarnDetailHandleBtnTableViewCell *cell = [WarnDetailHandleBtnTableViewCell cellWithTableView:tableView class:[WarnDetailHandleBtnTableViewCell class]];
        
        BMWeakSelf
        [cell setHandleBlock:^{
            [weakSelf handleWarn];
        }];
        
        return cell;
    }
    
    return [UITableViewCell new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row < 5) {
        return 44.f;
    }
    else if (indexPath.row == 5) {
        BOOL hasHandle = ![self.model.process_result boolValue];
        if (hasHandle) {
            return 44.f;
        }
        CGFloat height = [tableView fd_heightForCellWithIdentifier:NSStringFromClass([WarnDetailResultTableViewCell class]) cacheByIndexPath:indexPath configuration:^(WarnDetailResultTableViewCell *cell) {
            //赋值模型
            cell.model = self.model;
        }];
        
        return height < 95 ? 95 : height;
    }
    else if (indexPath.row == 6) {
        return 105;
    }
    else {
        return 0;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 2) {
        //设备
        [self gotoWatchVideoObserver];
    }
    else if (indexPath.row == 3) {
        //工厂
        [JumpTool gotoWorkAreaDetailWithAreaId:self.model.areaid navTitle:self.model.area_name vc:self];
    }
    else if (indexPath.row == 4) {
        //线路
        [JumpTool gotoLineDetailWithLineId:self.model.lineid vc:self];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == self.tableView) {
        if (_wmPlayer == nil || _wmPlayer.isFullscreen) {
            return;
        }
        
        if (_wmPlayer.superview) {
            CGRect rectInTableView = [self.headerView convertRect:self.headerView.videoImage.frame toView:self.tableView];
            if (rectInTableView.origin.y + rectInTableView.size.height < scrollView.contentOffset.y) {
                //暂停播放
                [_wmPlayer pause];
            }
            else {
                [_wmPlayer play];
            }
        }
    }
}

#pragma mark -

#pragma mark - 网络请求
- (void)requestWarnData {
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    Show_NoMsg
    BMWeakSelf
    [HttpRequest loadWarnDetailDataWithRecordId:self.model.recordid success:^(WarnDetailModel *object) {
        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeNone];
        Dismiss_NoMsg
        weakSelf.model = object;
        [weakSelf setupImageUrl];
        [weakSelf setupHeaderView];
    } failure:^(NSString *code, NSString *msg) {
        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeNone];
        Show_SV_Error_Msg(msg)
    }];
}

#pragma mark - 跳转设备
- (void)gotoWatchVideoObserver {
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];
    Show_Msg(@"请稍等...")
    BMWeakSelf
    [HttpRequest loadDeviceVideoDetailDataWithDeviceId:self.model.deviceid success:^(SelectVideoDeviceModel *object) {
        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeNone];
        Dismiss_NoMsg
        if ([object isKindOfClass:[SelectVideoDeviceModel class]]) {
            [JumpTool gotoWatchVideoVc:weakSelf deviceModel:object];
        }
    } failure:^(NSString *code, NSString *msg) {
        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeNone];
        Show_SV_Error_Msg(msg)
    }];
}

#pragma mark - 图片浏览器
- (NSString *)pictureView:(ESPictureBrowser *)pictureBrowser highQualityUrlStringForIndex:(NSInteger)index {
    return [self.imageUrlArray objectAtIndexSafe:index];
}

#pragma mark - 视频


- (void)playVideo {
    
    BMWeakSelf
    BOOL canStart = [BMUtils checkOpen4gPlayVideoWithCompletion:^{
        [weakSelf _playVideo];
    }];
    
    if (!canStart) {
        return;
    }
    [self _playVideo];
    
}

- (void)_playVideo {
    WMPlayerModel *model = [[WMPlayerModel alloc] init];
    model.title = @"";
    model.videoURL = [NSURL URLWithString:self.model.video_url?:@""];
    if (_wmPlayer) {
        [self releaseWMPlayer];
        _wmPlayer = [[WMPlayer alloc]initWithFrame:self.headerView.playButton.bounds];
        _wmPlayer.delegate = self;
        //关闭音量调节的手势
        //        wmPlayer.enableVolumeGesture = NO;
        _wmPlayer.backBtnStyle = BackBtnStyleClose;
        _wmPlayer.playerModel = model;
    }else{
        _wmPlayer = [[WMPlayer alloc]initWithFrame:self.headerView.playButton.bounds];
        _wmPlayer.delegate = self;
        _wmPlayer.backBtnStyle = BackBtnStyleClose;
        _wmPlayer.playerModel = model;
    }
    [self.headerView.playButton.superview addSubview:_wmPlayer];
    [_wmPlayer mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(_wmPlayer.superview);
    }];
    [_wmPlayer play];
}

-(void)releaseWMPlayer{
    //堵塞主线程
    [_wmPlayer pause];
    [_wmPlayer removeFromSuperview];
    _wmPlayer = nil;
}

-(void)wmplayer:(WMPlayer *)wmplayer clickedCloseButton:(UIButton *)closeBtn {
    [self releaseWMPlayer];
}

///全屏按钮
-(void)wmplayer:(WMPlayer *)wmplayer clickedFullScreenButton:(UIButton *)fullScreenBtn{
    if (_wmPlayer.isFullscreen) {//全屏
        //强制翻转屏幕，Home键在下边。
        [self toOrientation:UIInterfaceOrientationPortrait];
//        [[UIDevice currentDevice] setValue:@(UIInterfaceOrientationPortrait) forKey:@"orientation"];
    }else{//非全屏
        [self toOrientation:UIInterfaceOrientationLandscapeRight];
//        [[UIDevice currentDevice] setValue:@(UIInterfaceOrientationLandscapeRight) forKey:@"orientation"];
    }
    //刷新
//    [UIViewController attemptRotationToDeviceOrientation];
}

///单击播放器
-(void)wmplayer:(WMPlayer *)wmplayer singleTaped:(UITapGestureRecognizer *)singleTap{
    [self setNeedsStatusBarAppearanceUpdate];
}

//操作栏隐藏或者显示都会调用此方法
-(void)wmplayer:(WMPlayer *)wmplayer isHiddenTopAndBottomView:(BOOL)isHidden{
    [self setNeedsStatusBarAppearanceUpdate];
}

//点击进入,退出全屏,或者监测到屏幕旋转去调用的方法
-(void)toOrientation:(UIInterfaceOrientation)orientation{
    //获取到当前状态条的方向
    UIInterfaceOrientation currentOrientation = [UIApplication sharedApplication].statusBarOrientation;
    [_wmPlayer removeFromSuperview];
    //根据要旋转的方向,使用Masonry重新修改限制
    if (orientation ==UIInterfaceOrientationPortrait) {
        [self.headerView.playButton.superview addSubview:_wmPlayer];
        [UIView animateWithDuration:0.4 animations:^{
            _wmPlayer.transform = CGAffineTransformIdentity;
            [_wmPlayer mas_remakeConstraints:^(MASConstraintMaker *make) {
                make.edges.equalTo(_wmPlayer.superview);
            }];
            [_wmPlayer layoutIfNeeded];
        }];
        

        _wmPlayer.isFullscreen = NO;
    }else{
        [[UIApplication sharedApplication].keyWindow addSubview:_wmPlayer];
        _wmPlayer.isFullscreen = YES;
        if(currentOrientation ==UIInterfaceOrientationPortrait){
            if (NO) {
                [_wmPlayer mas_remakeConstraints:^(MASConstraintMaker *make) {
                    make.edges.equalTo(_wmPlayer.superview);
                }];
            }else{
                [UIView animateWithDuration:0.4 animations:^{
                    _wmPlayer.transform = CGAffineTransformMakeRotation(-M_PI_2);
                    [_wmPlayer mas_remakeConstraints:^(MASConstraintMaker *make) {
                        make.width.equalTo(@([UIScreen mainScreen].bounds.size.height));
                        make.height.equalTo(@([UIScreen mainScreen].bounds.size.width));
                        make.center.equalTo(_wmPlayer.superview);
                    }];
                    [_wmPlayer layoutIfNeeded];
                }];
                
            }

        }else{
            if (NO) {
                [_wmPlayer mas_remakeConstraints:^(MASConstraintMaker *make) {
                    make.edges.equalTo(_wmPlayer.superview);
                }];
            }else{
                [_wmPlayer mas_remakeConstraints:^(MASConstraintMaker *make) {
                    make.width.equalTo(@([UIScreen mainScreen].bounds.size.width));
                    make.height.equalTo(@([UIScreen mainScreen].bounds.size.height));
                    make.center.equalTo(_wmPlayer.superview);
                }];
            }

        }
    }
    //iOS6.0之后,设置状态条的方法能使用的前提是shouldAutorotate为NO,也就是说这个视图控制器内,旋转要关掉;
    //也就是说在实现这个方法的时候-(BOOL)shouldAutorotate返回值要为NO
    if (YES) {
        [self setNeedsStatusBarAppearanceUpdate];
    }else{
        [[UIApplication sharedApplication] setStatusBarOrientation:orientation animated:NO];
        //更改了状态条的方向,但是设备方向UIInterfaceOrientation还是正方向的,这就要设置给你播放视频的视图的方向设置旋转
        //给你的播放视频的view视图设置旋转
        [UIView animateWithDuration:0.4 animations:^{
            _wmPlayer.transform = CGAffineTransformIdentity;
            _wmPlayer.transform = [WMPlayer getCurrentDeviceOrientation];
            [_wmPlayer layoutIfNeeded];
            [self setNeedsStatusBarAppearanceUpdate];
        }];
    }
}
//
///**
// *  旋转屏幕通知
// */
//- (void)onDeviceOrientationChange:(NSNotification *)notification{
//    if (_wmPlayer.isLockScreen){
//        return;
//    }
//    UIDeviceOrientation orientation = [UIDevice currentDevice].orientation;
//    UIInterfaceOrientation interfaceOrientation = (UIInterfaceOrientation)orientation;
//    switch (interfaceOrientation) {
//        case UIInterfaceOrientationPortraitUpsideDown:{
//            NSLog(@"第3个旋转方向---电池栏在下");
//        }
//            break;
//        case UIInterfaceOrientationPortrait:{
//            NSLog(@"第0个旋转方向---电池栏在上");
//            [self toOrientation:UIInterfaceOrientationPortrait];
//        }
//            break;
//        case UIInterfaceOrientationLandscapeLeft:{
//            NSLog(@"第2个旋转方向---电池栏在左");
//            [self toOrientation:UIInterfaceOrientationLandscapeLeft];
//        }
//            break;
//        case UIInterfaceOrientationLandscapeRight:{
//            NSLog(@"第1个旋转方向---电池栏在右");
//            [self toOrientation:UIInterfaceOrientationLandscapeRight];
//        }
//            break;
//        default:
//            break;
//    }
//}

//全屏的时候hidden底部homeIndicator
-(BOOL)prefersHomeIndicatorAutoHidden{
    return _wmPlayer.isFullscreen;
}

-(BOOL)prefersStatusBarHidden{
    return _wmPlayer.prefersStatusBarHidden;
}

//viewController所支持的全部旋转方向
//- (UIInterfaceOrientationMask)supportedInterfaceOrientations{
//    return UIInterfaceOrientationMaskAllButUpsideDown;
//}

//视图控制器实现的方法
//- (BOOL)shouldAutorotate{
//    if (_wmPlayer.playerModel.verticalVideo) {
//        return NO;
//    }
//    return !_wmPlayer.isLockScreen;
//}

//-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
//    //对于present出来的控制器，要主动的（强制的）选择VC，让wmPlayer全屏
//    //    UIInterfaceOrientationLandscapeLeft或UIInterfaceOrientationLandscapeRight
//    [[UIDevice currentDevice] setValue:@(UIInterfaceOrientationLandscapeRight) forKey:@"orientation"];
//    return UIInterfaceOrientationLandscapeRight;
//}

- (void)dealloc {
    [self releaseWMPlayer];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
